import  {  NextRequest, NextResponse } from 'next/server'
import { format } from 'date-fns' //时间处理插件
import md5 from 'md5' //加密
import { encode } from 'js-base64'
import axiosrequest from 'service/fetch'
import { getIronSession  } from "iron-session"; //缓存
import { ironOptions } from "config/index"; //缓存配置
import { cookies } from 'next/headers';

// 解决ts报错
interface a {
  save(): unknown
  verifyCode: number
}

export const POST = async (req: NextRequest,res:NextResponse) =>{
  // 容联云平台个人id及token、appid 
  const AppId = '2c94811c8cd4da0a018f0ed2724d6ee0'
  const AccountId = '2c94811c8cd4da0a018f0ed270cd6ed9'
  const AuthToken = '53b008fc5a3a4e1db57bc675070b3c84'
  // 时间戳插件 date-fns
  const NowDate = format(new Date(),'yyyyMMddHHmmss')
  // 请求数据
  const SigParameter = md5(`${AccountId}${AuthToken}${NowDate}`)
  // 请求头部
  const Authorization = encode(`${AccountId}:${NowDate}`)
  // 短信平台请求接口
  const url = `https://app.cloopen.com:8883/2013-12-26/Accounts/${AccountId}/SMS/TemplateSMS?sig=${SigParameter}`
  // 四位随机数
  const verifyCode = Math.floor(Math.random() * (9000 - 1000) + 1000)
  console.log('verifyCode=>',verifyCode)
  // 过期时间
  const expireMinute = '5'
  const { to = '', templateId = '1' } = await req.json()
  try {
    // 请求数据
    const response = await axiosrequest.post(url,{
      to,
      templateId,
      appId:AppId,
      datas:[verifyCode,expireMinute]
    },{
      headers:{
        Authorization
      }
    })
    const { statusCode,statusMsg} = response as any
    if(statusCode === '000000'){
      // 缓存验证码verifyCode
      const session = await getIronSession(cookies(),ironOptions) as a;
      session.verifyCode = verifyCode;
      await session.save();
      return  NextResponse.json({msg:'短信发送成功，请注意查收！',code:200},{status:200})
    }else{
      return NextResponse.json({msg:statusMsg},{status:200})
    }
  } catch (error) {
    return  NextResponse.json({msg:error},{status:200})
  }
}
